<template>
  <div class="page-all-content-pr">
    <!-- 左侧内容 -->
    <div class="left-panel-container">
      <div class="img_left_title">
        <img src="../assets/img/module2/content.png" style="width: 100%" />
        <img src="../assets/img/module2/snailtitleicon.png" style="position: absolute; top: -10%; left: 6%" />
        <span class="text_left_title">空域使用需求</span>

      </div>

      <button v-if="!tableVisible" class="table-button-display" @click="tableVisible = true"></button>
      <button v-if="tableVisible" class="table-button-hidden" @click="tableVisible = false"></button>

      <!-- 功能输入按钮部分 -->
      <div v-if="tableVisible" class="table-actions">
        <!-- 搜索框 -->
        <input type="text" v-model="searchQuery" placeholder="请输入关键字" class="search-input" />
        <!-- 查询按钮 -->
        <button @click="filterTable" class="filter-button"></button>
        <!-- 排序选择 -->
        <select v-model="selectedSort" class="sort-select" @change="sortTable">
          <option value="application_acceptance_time" class="sort-select-item">按时间最新</option>
          <option value="id" class="sort-select-item">按序号排序</option>
        </select>
        <button @click="sortInverse" class="sort-button"></button>
        <!-- <el-switch v-model="switchValue" active-color="#13ce66" inactive-color="#3f93ff" @change="handleSwitchChange">
        </el-switch> -->
      </div>

      <!-- 表格内容 -->
      <div v-if="tableVisible" class="table-context">
        <CustomTable :customTableData="tableData" :columns="columns" @rowClick="handleRowClick"
          @viewDetails="handleViewDetails" @hoverLeave="hoverLeave" @viewDetailsHover="handleViewDetailsHover"
          @open-dialog="handleOpenDialog" height="100%" ref="customTable"
          @view-plan-trigger="handleViewPlanToModule3" />
      </div>
    </div>

    <!-- 右侧内容 -->
    <!-- <custom-dialog v-if="selectedRow" :visible.sync="dialogVisible" :title="selectedTitle" :dialogData="selectedRow" 
    @status-updated="fetchAirspaceDemand" /> -->
    <div v-if="dialogVisible" class="right-panel-container">
      <CustomDialog v-if="dialogVisible" :application="selectedApplication" :visible.sync="dialogVisible"
        :title="selectedTitle" :dialogData="selectedRow" :viewer="viewer"></CustomDialog>
    </div>
  </div>
</template>

<script>

import CustomTable from '@/components/CustomTableModule2PlanningRelease1.vue';
import { drawCylinderAreaM1, draw3DRectangularPipelineTrackM1_2, draw3DPolygonalPrismM1 } from '@/utils/draw3D-module2.js';
// import CustomDialog from '@/components/CustomDialogModuleshiyan.vue';
import CustomDialog from '@/components/CustomDialogModule1New.vue';
// import CustomDialog from '@/components/shiyan1.vue';
import axios from 'axios';

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE2;

export default {
  name: "Module2PlanningRelease",
  props: {
    cesiumViewer: {
      type: Object,
      required: true
    },
  },
  components: {
    CustomTable,
    CustomDialog,
  },
  data() {
    return {
      dialogVisible: false,
      selectedApplication: {  // 初始化默认值
        applicant: '',
        aircraftModel: '',
        applicationId: '',
        applicationAcceptanceTime: '',
        isRoundTrip: '',
        taskType: '',
        taskStartTime: '',              // 任务开始时间
        taskEndTime: '',                // 任务结束时间
        flightFrequency: '',            // 飞行频次
      },
      tableVisible: true, // 表格显示
      statusDialogVisible: false,  // 状态弹窗显示
      cofirmReleaseDialogVisible: false,
      userChooseDialogVisible: false,
      rightDialogVisible: false, // 右侧弹窗显示状态
      selectedDetails: {}, // 存储选中的行数据
      selectedSort: 'id', // 默认按序号排序
      searchQuery: '',  // 搜索关键字
      inverseSort: true, // 排序顺序，默认升序
      fileList: [], // 上传文件列表
      tableData: [], // 表格数据从服务器获取
      userList: [], // 用户列表
      gisdata: [],
      entityMap: {},
      viewer: null,
      currentLabelEntity: null,
      currentColor: null,
      currentEntityType: null,
      columns: [
        { prop: 'userName', label: '用户名', width: '25%' },
        { prop: 'applicationAcceptanceTime', label: '申请时间', width: '45%' },
        { prop: 'approvalStatus', label: '审核状态', width: '47%' },
      ],
      switchValue: false, // switch 开关的状态
      initialCesiumEntities: [], // 存储：Module1 首次渲染的初始 Cesium 实体
      hasStoredInitialEntities: false // 标记：是否已存储初始数据（避免重复存储）
    }
  },
  props: {
    cesiumViewer: {
      type: Object,
      required: true
    }
  },
  created() {
    // 页面加载时获取数据
    this.fetchTableData();
    this.fetchUserData();
    // 将传入的 viewer 实例赋值给组件的 data
    this.viewer = this.cesiumViewer
    console.log("Module6子组件获得的this.viewer", this.viewer)
  },
  methods: {
    // 获取GIS数据
    async drawgis(row) {
      try {
        this.viewer.entities.removeAll();
        this.refreshGISdata(); // 刷新gis数据
        this.fetchGISData(row); // 获取gis数据

        const { circular, polygonal, straight } = this.gisdata;
        const entitiesToFlyTo = [];
        console.log("规划方案页面绘制GIS的数据", this.gisdata)

        // 绘制圆柱体
        if (circular.length > 0) {
          circular.forEach((coord, index) => {
            const entity = drawCylinderAreaM1(
              this.viewer,
              coord.longitude,
              coord.latitude,
              coord.minAltitude,
              coord.maxAltitude,
              coord.radius,
              coord.color,
              0.2,
              coord.text,
            );
            if (entity) {
              entity.properties = new Cesium.PropertyBag({
                index: coord.index,  // 自定义index字段
                activeIndex: coord.activeidentityid,  // 自定义activeIndex字段
                type: 'circular',
              });

              //暂时去掉
              // this.gisdata.circular[index].entity = entity; 
              this.addEntity(coord.activeidentityid, coord.index, entity);
              entitiesToFlyTo.push(entity);
            }
          });
        }

        // 绘制多边形柱体
        if (polygonal.length > 0) {
          polygonal.forEach((track, index) => {
            // 检查 coordinates 是否存在且长度大于0
            if (track.coordinates && Array.isArray(track.coordinates) && track.coordinates.length > 0) {
              // console.log("绘制多边形柱状体传入的数据", track)
              // console.log("经纬度坐标信息", track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat())
              // console.log("最小高度", track.minAltitude)

              const entity = draw3DPolygonalPrismM1(
                this.viewer,
                track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat(),
                track.minAltitude,
                track.maxAltitude,
                track.color,
                0.2,
                track.text
              );
              // console.log("entity", entity)
              // console.log("index", index)
              if (entity) {
                entity.properties = new Cesium.PropertyBag({
                  index: track.index,  // 自定义index字段
                  activeIndex: track.activeidentityid,  // 自定义activeIndex字段
                  type: 'polygonal', //多变形体设置为1，为了后续改颜色获取实体本体
                });
                entitiesToFlyTo.push(entity);
                this.addEntity(track.activeidentityid, track.index, entity);
              }
            } else {
              console.log(`Track ${index} 的 coordinates 数据为空或未定义`);
            }
          });
        }


        // 绘制长方体管道轨迹
        if (straight.length > 0) {
          console.log("绘制长方体管道传入的数据", straight);
          straight.forEach((track, index) => {
            // const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, coord.altitude]).flat();
            const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, track.maxAltitude]).flat();
            const pointNames = track.activeidentityid; // 获取每个轨迹点的名字

            // Ensure sizes array has the correct length
            // const sizes = new Array(coordinates.length / 3 - 1).fill([100, 50]); // 对应生成每段长宽
            const sizes = new Array(coordinates.length / 3 - 1).fill([100, track.maxAltitude - track.minAltitude]);

            // Check if sizes length matches coordinates length - 1
            if (sizes.length !== coordinates.length / 3 - 1) {
              console.error('Sizes array length does not match coordinates array length minus one');
            } else {
              const entities = draw3DRectangularPipelineTrackM1_2(
                this.viewer,
                coordinates,
                sizes,
                0.2,
                track.color,
                track.text,
                // pointNames // 传递轨迹点名字数组
              );
              if (entities) {
                // console.log("typeof entities",entities);
                entities.forEach((entity, num) => {
                  entity.properties = new Cesium.PropertyBag({
                    index: track.index,  // 自定义index字段
                    activeIndex: track.activeidentityid,  // 自定义activeIndex字段,
                    type: 'straight',
                  });

                  entitiesToFlyTo.push(entity);
                  console.log('添加实体', num)
                })
                //暂时去掉
                this.addEntity(track.activeidentityid, track.index, entities);
              }
            }
          });
        }

        // 调整实体视角
        if (entitiesToFlyTo.length > 0) {
          this.viewer.flyTo(entitiesToFlyTo, {
            duration: 2,
            offset: {
              heading: Cesium.Math.toRadians(0),
              pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些

            }
          });
        }

        console.log("entityMap", this.entityMap)

        // 鼠标左键点击事件
        this.viewer.screenSpaceEventHandler.setInputAction((movement) => {
          // 清除之前的标签实体
          // if (currentLabelEntity) {
          //   this.viewer.entities.remove(currentLabelEntity);
          //   currentLabelEntity = null;
          // }
          const pickedObject = this.viewer.scene.pick(movement.position, 5);

          if (pickedObject && pickedObject.id && pickedObject.id.properties && pickedObject.id.properties.activeIndex) {
            const id1 = pickedObject.id.properties.activeIndex.getValue()
            const id2 = pickedObject.id.properties.index.getValue()
            const type = pickedObject.id.properties.type.getValue()
            this.$refs.statusDialog.clickGis(id1, id2)
            this.viewer.flyTo(this.getEntity(id1, id2), {
              duration: 2,
              offset: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些
                range: 16000
              }
            })

            this.entityChangeColor(this.getEntity(id1, id2), type)
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
        console.log('方案地图组件渲染成功');
      } catch (error) {
        console.error('方案地图组件渲染失败', error);
      }
    },
    // Module1 中处理 CustomTable 的“查看方案”事件
    handleViewPlanToModule3() {
      // 1. 核心新增：清空 Module1 自己绘制的所有 Cesium 实体
      // 从 entityMap 中提取所有 Module1 实体（entityMap 是 Module1 存储自身实体的容器）
      const module1Entities = Object.values(this.entityMap)
        .flat() // 扁平化数组（因为 entityMap 的值可能是实体数组，如航路实体）
        .filter(entity => entity); // 过滤空值，避免异常

      // 遍历删除所有 Module1 实体
      if (module1Entities.length > 0) {
        module1Entities.forEach(entity => {
          this.viewer.entities.remove(entity);
        });
        console.log(`Module1 切换到 Module3：已清空 ${module1Entities.length} 个自身实体`);
      }

      // 2. 清空 entityMap（避免下次绘制时残留旧数据）
      this.entityMap = {};

      // 3. 通知父组件（CombinedModule）切换到 Module3
      this.$emit('switch-to-module3');
    },
    handleSwitchChange(val) {
      console.log('自动审批开关状态改变:', val)
    },
    // 打开批量审批弹窗
    handleOpenDialog() {
      this.$emit('open-dialog'); // 通知父组件打开弹窗
    },
    entityChangeColor(entityAgent, type) {
      // 上一个点击的实体恢复颜色
      if (this.currentLabelEntity) {
        this.currentColor.alpha = 0.2;
        if (this.currentEntityType == 'straight') {
          this.currentLabelEntity.forEach(entity => {
            if (entity.material && entity.material.color) {
              entity.material.color = this.currentColor;
            }
          });
        } else {
          if (this.currentLabelEntity.material && this.currentLabelEntity.material.color) {
            this.currentLabelEntity.material.color = this.currentColor;
          }
        }
      }

      // 更新当前实体的种类
      this.currentEntityType = type;

      // 对当前点击的实体进行颜色变化
      if (type === 'circular') {
        this.currentLabelEntity = entityAgent.cylinder;
      } else if (type === 'polygonal') {
        this.currentLabelEntity = entityAgent.polygon;
      } else if (type === 'straight') {
        this.currentLabelEntity = entityAgent.map(entity => entity.corridor);
      }

      if (this.currentEntityType == 'straight') {
        if (this.currentLabelEntity && this.currentLabelEntity[0] && this.currentLabelEntity[0].material && this.currentLabelEntity[0].material.color) {
          this.currentColor = this.currentLabelEntity[0].material.color.getValue(Cesium.JulianDate.now()).clone();
          this.currentColor.alpha = 1;
          this.currentLabelEntity.forEach(entity => {
            if (entity.material && entity.material.color) {
              entity.material.color = this.currentColor;
            }
          });
        } else {
          console.error('Error: No valid material found for straight entities');
        }
      } else {
        if (this.currentLabelEntity && this.currentLabelEntity.material && this.currentLabelEntity.material.color) {
          this.currentColor = this.currentLabelEntity.material.color.getValue(Cesium.JulianDate.now()).clone();
          this.currentColor.alpha = 1;
          this.currentLabelEntity.material.color = this.currentColor;
        } else {
          console.error('Error: No valid material found for the entity');
        }
      }
      console.log('完成实体的变色');
    },
    // 销毁Cesium实例
    cesiumDestroy() {
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
      console.log(this.viewer);
    },
    async fetchGISData(row) {
      console.log('row.takeoffLandInfo', row.takeoffLandInfo)
      console.log('row.airlineInfo', row.airlineInfo)
      console.log('row.workInfo', row.workInfo)
      console.log('row.specialInfo', row.specialInfo)
      // 更新GIS数据，使gisdata的值符合作图的形式
      row.takeoffLandInfo && row.takeoffLandInfo.forEach((detail, index) => {
        console.log('正在处理起降机场数据:', detail)
        this.takeofflandpush(detail, index, 'main1')
      });


      // 遍历航路信息并根据 type 使用不同的颜色绘制
      row.airlineInfo && row.airlineInfo.forEach((detail, index) => {
        detail.shapes[0].shapes.forEach(shape => {
          let color = 'RED'; // 默认颜色为红色
          switch (detail.type) {
            case 0:
              color = 'CHOCOLATE';  // 低速航路
              break;
            case 1:
              color = 'ORANGE';  // 中速航路
              break;
            case 2:
              color = 'CORNFLOWERBLUE';  // 高速航路
              break;
            case 3:
              color = "DARKCYAN";  // 匝道
              break;
          }

          this.straightpush(
            shape.points,              // 点数据
            shape.minAltitude,         // 底部高度
            shape.maxAltitude,         // 顶部高度
            index,                     // 索引
            'main2',                   // 信息 ID
            detail.name,               // 航路名称
            color                   // 颜色（示例）
          );
          console.log(`多边形柱体航路（类型 ${detail.type}）更新`);
        });
      });

      // 遍历作业区信息并根据 shapeType 调用相应的绘制方法
      row.workInfo && row.workInfo.forEach((detail, index) => {
        detail.shapes[0].shapes.forEach(shape => {
          if (shape.shapeType === 1) { // 圆柱体类型 1
            this.cirularpush(shape, index, 'main3', detail.name, 'CYAN');
            console.log('圆柱体更新');
          } else if (shape.shapeType === 2) { // 另一种圆柱体类型 2（目前使用相同绘制方法）
            this.cirularpush(shape, index, 'main3', detail.name, 'CYAN');
            console.log('圆柱体（类型 2）更新');
          } else if (shape.shapeType === 3) { // 多边形柱体
            this.polygonalpush(shape, index, 'main3', detail.name, 'CYAN');
            console.log('多边形柱体更新');
          }
        });
      });

      // 遍历特殊区域信息并根据 shapeType 调用相应的绘制方法
      row.specialInfo && row.specialInfo.forEach((detail, index) => {
        detail.shapes[0].shapes.forEach(shape => {
          if (shape.shapeType === 1) { // 圆形柱体
            this.cirularpush(shape, index, 'main4', detail.name, 'RED');
            console.log('圆形柱体更新');
          } else if (shape.shapeType === 2) { // 另一种圆形柱体类型
            this.cirularpush(shape, index, 'main4', detail.name, 'RED');
            console.log('圆形柱体（类型 2）更新');
          } else if (shape.shapeType === 3) { // 多边形柱体类型
            // 创建一个新的多边形数据对象
            const polygonalData = {
              points: [],  // 存放每个点的数据
              coordinates: [],  // 存放多边形顶点的经纬度
              minAltitude: shape.minAltitude,  // 从 shape 获取最小高度
              maxAltitude: shape.maxAltitude,  // 从 shape 获取最大高度
              index: index,
              activeidentityid: 'main4',
              text: detail.name,
              color: 'RED'
            };

            // 如果存在 points 数组，遍历并提取经纬度信息
            if (shape.points && Array.isArray(shape.points) && shape.points.length > 0) {
              shape.points.forEach(point => {
                // 确保每个点都包含有效的经纬度信息
                if (point.latitude && point.longitude) {
                  // 添加点到 points 数组
                  polygonalData.points.push({
                    altitude: point.altitude,  // 如果有高度信息，存储
                    latitude: point.latitude,
                    longitude: point.longitude,
                    sequence: point.sequence,  // 如果有顺序信息，存储
                    shapeId: point.shapeId  // 如果有形状 ID，存储
                  });
                } else {
                  console.log("发现无效的点数据:", point);
                }
              });
            } else {
              console.log("没有可用的点数据 (shape.points 为空或未定义)");
            }

            // 检查是否有有效的坐标
            if (polygonalData.points.length > 0) {
              // 调用 polygonalpush 函数来绘制多边形柱体
              this.polygonalpush(polygonalData, index, 'main4', detail.name, 'RED');
              console.log('多边形柱体更新:', polygonalData);
            } else {
              console.log("没有有效的坐标数据，跳过该多边形柱体");
            }
          }
        });
      });
    },
    async fetchTableData() {
      try {
        const params = {
          currentPage: 1,
          size: 15,
          order: '时间最新',
          status: [0, 3]  // 0: 待审核, 1：已通过 2：被驳回 3: 审核中
        };

        // 如果关键字有值，则添加到params中
        if (this.keyText) {
          params.keyText = this.keyText;
        }

        console.log("使用需求页面获取所有数据时给后端发送的", params);
        const response = await axios.post(`${baseApi}/admin/airspaceDemand/keywordSearch`, params);
        console.log("response.data.data.pageData", response.data.data.pageData)
        // this.tableData = response.data.data.pageData.map((item, index) => ({
        this.tableData = response.data.data.pageData
          .filter(item => item.approvalStatus === 0 || item.approvalStatus === 3)
          .map((item, index) => ({
            applicationId: item.applicationId,
            userName: item.userName,
            applicationAcceptanceTime: (() => {
              // const date = new Date(item.applicationAcceptanceTime);
              const date = new Date(item.applicationReceiveTime);
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要+1
              const day = String(date.getDate()).padStart(2, '0');
              const hours = String(date.getHours()).padStart(2, '0');
              const minutes = String(date.getMinutes()).padStart(2, '0');
              const seconds = String(date.getSeconds()).padStart(2, '0');

              return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
            })(),
            // applicationAcceptanceTime: item.applicationAcceptanceTime,
            // approvalStatus: item.approvalStatus === 1 ? '审核通过' : item.approvalStatus === 0 ? '待审核' : '已驳回' // 根据状态值映射文本
            approvalStatus: item.approvalStatus === 0 ? '待审核' : '审核中'
          }));
      } catch (error) {
        console.error('获取表格数据失败', error);
      }
      console.log("this.tableData156", this.tableData)
    },
    //获取用户信息
    async fetchUserData() {
      try {
        // const response = await axios.get('http://47.99.75.194:8082/module2/GetPubUser', null, null);
        const response = await axios.get(`${baseApi}/airspaceUtilization/GetPubUser`, null, null);

        if (response.data.code === 0) {
          this.userList = response.data.data;
          console.log('获取用户信息');
          console.log(this.userList);
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
      }
    },
    sortTable() {
      // 重新获取排序后的数据
      this.fetchTableData();
    },
    sortInverse() {
      this.inverseSort = !this.inverseSort;
      // console.log(this.inverseSort);
      this.fetchTableData();
    },
    filterTable() {
      // 触发搜索过滤，重新获取数据
      this.fetchTableData();
    },
    refreshTable() {
      // 刷新表格数据，重置搜索和排序
      this.selectedSort = 'id';
      this.searchQuery = '';
      this.fetchTableData();
    },
    refreshHistory() {
      // 刷新历史数据，通知子组件完成
      setTimeout(() => { this.$refs.statusDialog.fetchHistoryData(this.selectedDetails.id); }, 100);
    },
    handleViewDetails(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
      this.cofirmReleaseDialogVisible = false; // 关闭确认弹窗 后续优化的话可以在弹窗时直接设置无法点击别处
      this.$refs.statusDialog.refreshChange();
      this.drawgis(row);
      this.$refs.statusDialog.fetchHistoryData(row.id);

    },
    handleViewDetailsHover(row) {
      this.selectedDetails = row; // 将点击的行数据保存
      this.statusDialogVisible = true; // 显示弹窗
    },
    handleRowClick(row) {
      this.selectedRow = row;
      console.log("选择的用户的行121", row);
      this.selectedTitle = row.applicationId;
      this.selectedApplication = {
        ...this.selectedApplication, // 保留默认值
        ...row,                     // 覆盖为行数据
        applicant: row.applicantOrganization,
        aircraftModel: row.aircraftModel
      }
      this.dialogVisible = true;
    },
    hoverLeave() {
      this.statusDialogVisible = false;
    },
    submitVisibleChange() {
      this.cofirmReleaseDialogVisible = true;
    },
    userVisibleChange() {
      this.userChooseDialogVisible = true;
    },

    refreshGISdata() {
      this.gisdata = {
        circular: [],
        polygonal: [],
        straight: []
      };
    },
    takeofflandpush(detail, index, infoid) {
      const shape = detail.shapes[0].shapes[0]; // 获取 shapes 中的第一个 shape 对象
      const centerPoint = shape.points[0]; // 圆心点坐标信息

      // 构建圆柱体的 GIS 数据
      this.gisdata.circular.push({
        longitude: centerPoint.longitude,
        latitude: centerPoint.latitude,
        minAltitude: shape.minAltitude,
        maxAltitude: shape.maxAltitude,
        radius: shape.rout, // 使用 rout 作为半径
        activeidentityid: infoid,
        index: index,
        color: 'YELLOW',
        text: detail.name + '区',
      });

      console.log("起降机场数据已添加至 GIS 数据:", this.gisdata.circular);
    },
    cirularpush(shape, index, infoid, text, color) {
      console.log("圆柱体 shape detail:", shape);

      // 圆柱体的中心点信息从 shape.points[0] 获取
      const centerPoint = shape.points[0];

      this.gisdata.circular.push({
        longitude: centerPoint.longitude,
        latitude: centerPoint.latitude,
        minAltitude: shape.minAltitude,
        maxAltitude: shape.maxAltitude,
        radius: shape.rout, // 使用 rout 作为半径
        activeidentityid: infoid,
        index: index,
        color: color,
        text: text,
      });

      console.log("圆柱体已添加至 GIS 数据:", this.gisdata.circular);
    },
    polygonalpush(shape, index, infoid, text, color) {
      console.log("多边形 detail:", shape);

      // 构建多边形数据
      const polygonalData = {
        coordinates: [],  // 存放多边形顶点的经纬度
        minAltitude: shape.minAltitude,  // 从 shape 获取最小高度
        maxAltitude: shape.maxAltitude,  // 从 shape 获取最大高度
        index: index,
        activeidentityid: infoid,
        text: text,
        color: color
      };

      // 检查 shape.points 是否存在且是一个数组
      if (shape.points && Array.isArray(shape.points) && shape.points.length > 0) {
        // 遍历 points 中的每个顶点并提取经纬度
        shape.points.forEach(point => {
          polygonalData.coordinates.push({
            longitude: point.longitude,
            latitude: point.latitude
          });
        });
      } else {
        console.log("没有可用的顶点数据 (shape.points 为空或未定义)");
      }


      // 添加到 GIS 数据结构的多边形列表中
      this.gisdata.polygonal.push(polygonalData);
      console.log("多边形柱体已添加至 GIS 数据:", this.gisdata.polygonal);
    },
    straightpush(points, minAltitude, maxAltitude, index, infoid, text, color) {
      console.log('点线形航路数据:', points);

      // 构建 straight 数据结构
      const straightData = {
        coordinates: [],           // 包含经纬度和高度的数组
        minAltitude: minAltitude,  // 底部高度
        maxAltitude: maxAltitude,  // 顶部高度
        index: index,
        activeidentityid: infoid,
        color: color,
        text: text
      };

      // 遍历 points，提取经纬度和高度信息
      points.forEach(point => {
        straightData.coordinates.push({
          longitude: point.longitude,
          latitude: point.latitude,
          altitude: point.altitude
        });
      });

      // 添加到 GIS 数据的 straight 部分
      this.gisdata.straight.push(straightData);
      console.log('straightData 已添加至 GIS 数据:', straightData);
    },
  },
  watch: {
    // 监听 statusDialogVisible 的变化
    statusDialogVisible(newValue, oldValue) {
      if (newValue === false && oldValue === true) {
        // 当 statusDialogVisible 从 1 变为 0 时，调用子组件的 resetSelection 方法
        this.$refs.customTable.resetSelection();
        // console.log('resetSelection called');
      }
    },
    dialogVisible(newVal, oldVal) {
      // 弹窗从打开变成关闭时触发，可能用户对需求进行了操作
      if (oldVal === true && newVal === false) {
        this.fetchTableData();
      }
    }
  }

}
</script>

<style scoped lang="css">
.cesiumContainerBox {
  width: 100%;
  position: relative;
  height: 80vh;
  margin: 0;
  padding: 0;

  .mapBg {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    pointer-events: none;
  }

  .layer {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 2;
    pointer-events: none;
    box-shadow: inset -200px 0px 60px -20px rgb(6 7 29 / 35%), inset 200px 0px 60px -20px rgb(6 7 29 / 35%);
  }

  .right-panel-container {
    width: auto;
    /* 改为自动宽度 */
    height: 100%;
    position: relative;
    /* 确保定位正确 */
    overflow: visible;
    /* 确保内容不会被裁剪 */
  }
}

/* 调整 switch 的位置 */
.el-switch {
  position: absolute;
  background-size: contain;
  /* 背景图片覆盖按钮大小 */
  background-repeat: no-repeat;
  background-color: transparent;
  color: transparent;
  left: 41%;
  top: 11%;
  height: 60%;
  z-index: 3;
  border: none;
  cursor: pointer;
}
</style>
<style scoped lang="css" src="../assets/indexModule1.css" />